import { getStore, setStore } from '@/utils/store'
import { getList } from "@/api/sys/dict";

const dict = {
  state: {
    Dict: getStore({ name: 'Dict' }) || {}, // 树形字典
    BisDict: getStore({ name: 'Bis_Dict' }) || {}, // 对象字典
  },
  actions: {
    getDict({ commit }) {
      return new Promise((resolve) => {
        getList().then(({ data }) => {
          commit('SET_DICT', data);
          resolve();
        })
      })
    },
  },
  mutations: {
    SET_DICT: (state, data) => {
      let row = {}
      let bisRow = {}
      for (const item of data) {
        if (item.parentId === "0") {
          row[item.dictCode] = { ...item, children: [] };
          bisRow[item.dictCode] = []
        } else {
          for (let key in row) {
            if (row[key].dictId === item.parentId) {
              row[key].children.push(item)
              bisRow[key].push(item)
            }
          }
        }
      }
      state.Dict = row
      state.BisDict = bisRow
      setStore({ name: 'Dict', content: state.Dict })
      setStore({ name: 'BisDict', content: state.BisDict })
    },
  }

};

export default dict;
